package view.usuario;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.ParseException;

import javax.swing.ButtonGroup;
import javax.swing.DefaultComboBoxModel;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFormattedTextField;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.border.EmptyBorder;
import javax.swing.text.MaskFormatter;

import com.toedter.calendar.JDateChooser;

import controller.ControladorExcecao;
import controller.ControladorUsuario;

import javax.swing.JCheckBox;
import javax.swing.JPasswordField;

import model.entidades.Usuario;
import utils.Constantes;
import utils.Criptografia;
import utils.Formatacao;
import view.componentes.CustomDocumentFilter;
import view.componentes.GenericPlainDocument;
import view.componentes.GenericWindowListener;
import view.principal.TelaPrincipal;


public class TelaCadastrarUsuario extends JDialog implements ActionListener {

	private static final long serialVersionUID = 1L;
	
	private JPanel panelNorte;
	private final JPanel panelCentro = new JPanel();
	private JPanel panelSul;
	
	private JLabel lblCadastrarUsuario;
	private JLabel lblDadosPessoais;
	private JLabel lblNomeCompleto; 
	private JLabel lblDataNascimento;
	private JLabel lblSexo;
	private JLabel lblCpf;
	private JLabel lblRg;
	private JLabel lblSituacao;
	private JLabel lblContato;
	private JLabel lblTelefone;
	private JLabel lblCelular;
	private JLabel label_1;
	private JLabel lblOrgaoEmissor;
	private JLabel lblEmail;
	private JLabel label;
	private JLabel lblDadosDeAcesso;
	private JLabel lblLogin;
	private JLabel lblSenha;
	private JLabel lblConfirmacaoSenha;
	
	private JTextField txtNomeCompleto;
	private JTextField txtRgNumero;
	private JTextField txtEmail;
	private JTextField txtLogin;
	private JTextField txtRgOrgao;
	
	private JFormattedTextField txtCpf;
	private JFormattedTextField txtTelefone;
	private JFormattedTextField txtCelular;
	
	private JPasswordField txtSenha;
	private JPasswordField txtConfirmaSenha;
	
	private MaskFormatter mascaraCpf;
	private MaskFormatter mascaraCep;
	private MaskFormatter mascaraTelefone;
	private MaskFormatter mascaraCelular;
	
	private JComboBox<String> comboBoxRgUF;

	private JRadioButton rdbtnMasculino;
	private JRadioButton rdbtnFeminino;
	private ButtonGroup grupoSexo;
	
	private JRadioButton rdbtnAtivo;
	private JRadioButton rdbtnInativo;
	private ButtonGroup grupoSituacao;
	
	private JCheckBox chckbxUsuarioAdministrador;
	
	private JButton btnSalvar;
	private JButton btnCancelar;
	
	private JDateChooser txtDataNascimento;
	
	private Usuario usuario;
	private JButton btnEditar;
	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {

		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
						if ("Nimbus".equals(info.getName())) {
							UIManager.setLookAndFeel(info.getClassName());
							break;
						}else{
							UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
						}
					}
					TelaCadastrarUsuario window = new TelaCadastrarUsuario(null);
					window.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});		
	}

	/**
	 * Create the dialog.
	 */
	public TelaCadastrarUsuario(Usuario usuario) {
		
		inicializaComponentes();
		chckbxUsuarioAdministrador.setVisible(false);
		if(usuario == null){
			limparCamposTexto();
			btnEditar.setVisible(false);
			this.usuario = new Usuario();
		} else {
			this.usuario = usuario;
			habilitaDesabilitaCampos(false);
			preencheCampos();
			if (TelaPrincipal.getUsuarioLogado().getTipoPerfil().equalsIgnoreCase(Constantes.TIPO_PERFIL_ADM)) {
				btnEditar.setVisible(true);
			} else {
				btnEditar.setVisible(false);
			}
		}
		
	}
	
	private void inicializaComponentes() {
		setBounds(100, 100, 600, 500);
		setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
		this.addWindowListener(new GenericWindowListener());
		setResizable(false);
		setModal(true);
		setLocationRelativeTo(null);
		getContentPane().setLayout(new BorderLayout());
		panelCentro.setBackground(Color.WHITE);
		panelCentro.setBorder(new EmptyBorder(5, 0, 5, 5));
		getContentPane().add(panelCentro, BorderLayout.CENTER);
		
		lblDadosPessoais = new JLabel("Dados Pessoais");
		lblDadosPessoais.setBorder(new EmptyBorder(0, 0, 0, 5));
		lblDadosPessoais.setHorizontalAlignment(SwingConstants.RIGHT);
		lblDadosPessoais.setOpaque(true);
		lblDadosPessoais.setBackground(Color.LIGHT_GRAY);
		lblDadosPessoais.setFont(new Font("Tahoma", Font.BOLD, 12));
		
		lblNomeCompleto = new JLabel("Nome Completo:");
		
		txtNomeCompleto = new JTextField();
		txtNomeCompleto.setDocument(new GenericPlainDocument(CustomDocumentFilter.criar(
				CustomDocumentFilter.SO_LETRAS, CustomDocumentFilter.MAIUSCULAS, 0)));
		txtNomeCompleto.setColumns(10);
		
		lblDataNascimento = new JLabel("Data Nascimento:");
		
		rdbtnMasculino = new JRadioButton("Masculino");
		rdbtnMasculino.setActionCommand(Constantes.SEXO_MASCULINO);
		rdbtnMasculino.setBackground(Color.WHITE);
		
		rdbtnFeminino = new JRadioButton("Feminino");
		rdbtnFeminino.setActionCommand(Constantes.SEXO_FEMININO);
		rdbtnFeminino.setBackground(Color.WHITE);
		
		grupoSexo = new ButtonGroup();
		grupoSexo.add(rdbtnMasculino);
		grupoSexo.add(rdbtnFeminino);
		grupoSexo.setSelected(rdbtnMasculino.getModel(), true);
		
		lblSexo = new JLabel("Sexo:");
		
		lblCpf = new JLabel("CPF:");
		
		try {
			mascaraCpf = new MaskFormatter("###.###.###-##");
			mascaraCpf.setPlaceholderCharacter('_');
		} catch (ParseException e) {
			e.printStackTrace();
		}
	    
		txtCpf = new JFormattedTextField(mascaraCpf);
		txtCpf.setColumns(10);
		
		txtRgNumero = new JTextField();
		txtRgNumero.setDocument(new GenericPlainDocument(CustomDocumentFilter.criar(
				CustomDocumentFilter.SO_NUMEROS, CustomDocumentFilter.MAIUSCULAS, 0)));
		txtRgNumero.setColumns(10);
		
		lblRg = new JLabel("RG:");
		
		lblSituacao = new JLabel("Situa\u00E7\u00E3o");
		
		try {
			mascaraCep = new MaskFormatter("##.###-###");
			mascaraCep.setPlaceholderCharacter('_');
		} catch (ParseException e) {
			e.printStackTrace();
		}
		
		lblContato = new JLabel("Contato");
		lblContato.setOpaque(true);
		lblContato.setHorizontalAlignment(SwingConstants.RIGHT);
		lblContato.setFont(new Font("Tahoma", Font.BOLD, 12));
		lblContato.setBorder(new EmptyBorder(0, 0, 0, 5));
		lblContato.setBackground(Color.LIGHT_GRAY);
		
		try {
			mascaraTelefone = new MaskFormatter("(##) ####-####");
			mascaraTelefone.setPlaceholderCharacter('_');
		} catch (ParseException e) {
			e.printStackTrace();
		}
		
		txtTelefone = new JFormattedTextField(mascaraTelefone);
		txtTelefone.setColumns(10);
		
		lblTelefone = new JLabel("Telefone:");
		
		try {
			mascaraCelular = new MaskFormatter("(##) ####-####");
			mascaraCelular.setPlaceholderCharacter('_');
		} catch (ParseException e) {
			e.printStackTrace();
		}
		
		txtCelular = new JFormattedTextField(mascaraCelular);
		txtCelular.setColumns(10);
		
		lblCelular = new JLabel("Celular:");
		
		txtDataNascimento = new JDateChooser();
		txtDataNascimento.getCalendarButton().setBackground(Color.WHITE);
		txtDataNascimento.setOpaque(false);
		
		label = new JLabel("-");
		label.setFont(new Font("SansSerif", Font.PLAIN, 16));
		
		txtRgOrgao = new JTextField();
		txtRgOrgao.setDocument(new GenericPlainDocument(CustomDocumentFilter.criar(
				CustomDocumentFilter.SO_LETRAS, CustomDocumentFilter.MAIUSCULAS, 0)));
		txtRgOrgao.setColumns(10);
		
		label_1 = new JLabel("/");
		label_1.setFont(new Font("SansSerif", Font.PLAIN, 16));
		
		comboBoxRgUF = new JComboBox<String>();
		comboBoxRgUF.setBackground(Color.WHITE);
		comboBoxRgUF.setModel(new DefaultComboBoxModel<String>(Constantes.SIGLAS_ESTADOS));
		
		lblOrgaoEmissor = new JLabel("Orgao Emissor / UF:");
		
		txtEmail = new JTextField();
		txtEmail.setDocument(new GenericPlainDocument(CustomDocumentFilter.criar(
				CustomDocumentFilter.SEM_RESTRICAO, CustomDocumentFilter.MINUSCULAS, 0)));
		txtEmail.setColumns(10);
		
		lblEmail = new JLabel("Email:");
		
		rdbtnAtivo = new JRadioButton("Ativo");
		rdbtnAtivo.setActionCommand(Constantes.ATIVO);
		rdbtnAtivo.setBackground(Color.WHITE);
		
		rdbtnInativo = new JRadioButton("Inativo");
		rdbtnInativo.setActionCommand(Constantes.INATIVO);
		rdbtnInativo.setBackground(Color.WHITE);
		
		grupoSituacao = new ButtonGroup();
		grupoSituacao.add(rdbtnAtivo);
		grupoSituacao.add(rdbtnInativo);
		grupoSituacao.setSelected(rdbtnAtivo.getModel(), true);
		
		lblDadosDeAcesso = new JLabel("Dados de Acesso");
		lblDadosDeAcesso.setOpaque(true);
		lblDadosDeAcesso.setHorizontalAlignment(SwingConstants.RIGHT);
		lblDadosDeAcesso.setFont(new Font("Tahoma", Font.BOLD, 12));
		lblDadosDeAcesso.setBorder(new EmptyBorder(0, 0, 0, 5));
		lblDadosDeAcesso.setBackground(Color.LIGHT_GRAY);
		
		lblLogin = new JLabel("Login:");
		
		txtLogin = new JTextField();
		txtLogin.setColumns(10);
		
		lblSenha = new JLabel("Senha:");
		
		txtSenha = new JPasswordField();
		txtSenha.setEchoChar('●');
		txtSenha.setColumns(10);
		
		txtConfirmaSenha = new JPasswordField();
		txtConfirmaSenha.setEchoChar('●');
		txtConfirmaSenha.setColumns(10);
		
		lblConfirmacaoSenha = new JLabel("Confirma\u00E7\u00E3o de Senha:");
		
		chckbxUsuarioAdministrador = new JCheckBox("Usu\u00E1rio Administrador");
		GroupLayout gl_panelCentro = new GroupLayout(panelCentro);
		gl_panelCentro.setHorizontalGroup(
			gl_panelCentro.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_panelCentro.createSequentialGroup()
					.addGroup(gl_panelCentro.createParallelGroup(Alignment.LEADING)
						.addGroup(gl_panelCentro.createParallelGroup(Alignment.LEADING, false)
							.addGroup(gl_panelCentro.createSequentialGroup()
								.addContainerGap()
								.addGroup(gl_panelCentro.createParallelGroup(Alignment.LEADING)
									.addGroup(gl_panelCentro.createSequentialGroup()
										.addGroup(gl_panelCentro.createParallelGroup(Alignment.LEADING, false)
											.addGroup(gl_panelCentro.createSequentialGroup()
												.addComponent(lblNomeCompleto)
												.addGap(219))
											.addGroup(gl_panelCentro.createSequentialGroup()
												.addComponent(txtNomeCompleto)
												.addGap(18)))
										.addGroup(gl_panelCentro.createParallelGroup(Alignment.LEADING)
											.addGroup(gl_panelCentro.createSequentialGroup()
												.addComponent(lblDataNascimento)
												.addGap(36)
												.addComponent(lblSexo))
											.addComponent(txtDataNascimento, GroupLayout.PREFERRED_SIZE, 124, GroupLayout.PREFERRED_SIZE))
										.addPreferredGap(ComponentPlacement.RELATED)
										.addGroup(gl_panelCentro.createParallelGroup(Alignment.LEADING)
											.addComponent(rdbtnMasculino)
											.addComponent(rdbtnFeminino)))
									.addGroup(gl_panelCentro.createSequentialGroup()
										.addGroup(gl_panelCentro.createParallelGroup(Alignment.LEADING)
											.addComponent(txtCpf, GroupLayout.PREFERRED_SIZE, 101, GroupLayout.PREFERRED_SIZE)
											.addComponent(lblCpf))
										.addGap(18)
										.addGroup(gl_panelCentro.createParallelGroup(Alignment.LEADING)
											.addComponent(lblRg)
											.addComponent(txtRgNumero, GroupLayout.PREFERRED_SIZE, 103, GroupLayout.PREFERRED_SIZE))
										.addPreferredGap(ComponentPlacement.RELATED)
										.addComponent(label)
										.addPreferredGap(ComponentPlacement.RELATED)
										.addGroup(gl_panelCentro.createParallelGroup(Alignment.LEADING)
											.addGroup(gl_panelCentro.createSequentialGroup()
												.addComponent(txtRgOrgao, 0, 0, Short.MAX_VALUE)
												.addGap(5)
												.addComponent(label_1)
												.addPreferredGap(ComponentPlacement.RELATED)
												.addComponent(comboBoxRgUF, GroupLayout.PREFERRED_SIZE, 58, GroupLayout.PREFERRED_SIZE))
											.addComponent(lblOrgaoEmissor))
										.addPreferredGap(ComponentPlacement.UNRELATED)
										.addGroup(gl_panelCentro.createParallelGroup(Alignment.LEADING, false)
											.addComponent(rdbtnAtivo, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
											.addComponent(lblSituacao, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
										.addPreferredGap(ComponentPlacement.RELATED)
										.addComponent(rdbtnInativo)
										.addGap(79)))
								.addGap(3))
							.addComponent(lblDadosPessoais, GroupLayout.PREFERRED_SIZE, 188, GroupLayout.PREFERRED_SIZE))
						.addComponent(lblContato, GroupLayout.PREFERRED_SIZE, 127, GroupLayout.PREFERRED_SIZE)
						.addGroup(gl_panelCentro.createSequentialGroup()
							.addContainerGap()
							.addGroup(gl_panelCentro.createParallelGroup(Alignment.LEADING)
								.addComponent(txtTelefone, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
								.addComponent(lblTelefone))
							.addGap(18)
							.addGroup(gl_panelCentro.createParallelGroup(Alignment.LEADING)
								.addComponent(txtCelular, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
								.addComponent(lblCelular))
							.addGap(18)
							.addGroup(gl_panelCentro.createParallelGroup(Alignment.LEADING)
								.addComponent(lblEmail)
								.addComponent(txtEmail, GroupLayout.PREFERRED_SIZE, 228, GroupLayout.PREFERRED_SIZE)))
						.addGroup(gl_panelCentro.createSequentialGroup()
							.addContainerGap()
							.addComponent(lblLogin))
						.addGroup(gl_panelCentro.createSequentialGroup()
							.addGroup(gl_panelCentro.createParallelGroup(Alignment.LEADING)
								.addGroup(gl_panelCentro.createParallelGroup(Alignment.LEADING, false)
									.addGroup(gl_panelCentro.createSequentialGroup()
										.addContainerGap()
										.addComponent(txtSenha))
									.addGroup(gl_panelCentro.createSequentialGroup()
										.addContainerGap()
										.addComponent(txtLogin))
									.addComponent(lblDadosDeAcesso, GroupLayout.PREFERRED_SIZE, 188, GroupLayout.PREFERRED_SIZE))
								.addGroup(gl_panelCentro.createSequentialGroup()
									.addContainerGap()
									.addComponent(lblSenha)))
							.addGap(18)
							.addGroup(gl_panelCentro.createParallelGroup(Alignment.LEADING)
								.addComponent(chckbxUsuarioAdministrador)
								.addComponent(lblConfirmacaoSenha)
								.addComponent(txtConfirmaSenha, GroupLayout.PREFERRED_SIZE, 182, GroupLayout.PREFERRED_SIZE))))
					.addContainerGap(11, Short.MAX_VALUE))
		);
		gl_panelCentro.setVerticalGroup(
			gl_panelCentro.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_panelCentro.createSequentialGroup()
					.addContainerGap()
					.addComponent(lblDadosPessoais)
					.addPreferredGap(ComponentPlacement.UNRELATED)
					.addGroup(gl_panelCentro.createParallelGroup(Alignment.LEADING)
						.addGroup(gl_panelCentro.createSequentialGroup()
							.addGroup(gl_panelCentro.createParallelGroup(Alignment.BASELINE)
								.addComponent(rdbtnMasculino)
								.addComponent(lblSexo)
								.addComponent(lblDataNascimento))
							.addPreferredGap(ComponentPlacement.UNRELATED)
							.addComponent(rdbtnFeminino))
						.addGroup(gl_panelCentro.createSequentialGroup()
							.addGroup(gl_panelCentro.createParallelGroup(Alignment.LEADING)
								.addComponent(lblNomeCompleto)
								.addGroup(gl_panelCentro.createSequentialGroup()
									.addGap(22)
									.addGroup(gl_panelCentro.createParallelGroup(Alignment.BASELINE)
										.addComponent(txtNomeCompleto, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
										.addComponent(txtDataNascimento, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))))
							.addPreferredGap(ComponentPlacement.RELATED)
							.addGroup(gl_panelCentro.createParallelGroup(Alignment.LEADING)
								.addComponent(lblCpf)
								.addComponent(lblRg)
								.addGroup(gl_panelCentro.createParallelGroup(Alignment.BASELINE)
									.addComponent(lblOrgaoEmissor)
									.addComponent(lblSituacao)))
							.addPreferredGap(ComponentPlacement.RELATED)
							.addGroup(gl_panelCentro.createParallelGroup(Alignment.BASELINE)
								.addComponent(txtCpf, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
								.addComponent(txtRgNumero, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
								.addComponent(label)
								.addComponent(txtRgOrgao, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
								.addComponent(label_1)
								.addComponent(comboBoxRgUF, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
								.addComponent(rdbtnAtivo)
								.addComponent(rdbtnInativo))))
					.addPreferredGap(ComponentPlacement.UNRELATED)
					.addComponent(lblContato, GroupLayout.PREFERRED_SIZE, 15, GroupLayout.PREFERRED_SIZE)
					.addPreferredGap(ComponentPlacement.RELATED, 9, Short.MAX_VALUE)
					.addGroup(gl_panelCentro.createParallelGroup(Alignment.BASELINE)
						.addComponent(lblTelefone)
						.addComponent(lblCelular)
						.addComponent(lblEmail))
					.addPreferredGap(ComponentPlacement.RELATED)
					.addGroup(gl_panelCentro.createParallelGroup(Alignment.BASELINE)
						.addComponent(txtTelefone, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
						.addComponent(txtCelular, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
						.addComponent(txtEmail, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
					.addPreferredGap(ComponentPlacement.UNRELATED)
					.addComponent(lblDadosDeAcesso, GroupLayout.PREFERRED_SIZE, 15, GroupLayout.PREFERRED_SIZE)
					.addPreferredGap(ComponentPlacement.UNRELATED)
					.addComponent(lblLogin)
					.addPreferredGap(ComponentPlacement.RELATED)
					.addGroup(gl_panelCentro.createParallelGroup(Alignment.BASELINE)
						.addComponent(txtLogin, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
						.addComponent(chckbxUsuarioAdministrador))
					.addPreferredGap(ComponentPlacement.UNRELATED)
					.addGroup(gl_panelCentro.createParallelGroup(Alignment.BASELINE)
						.addComponent(lblSenha)
						.addComponent(lblConfirmacaoSenha))
					.addPreferredGap(ComponentPlacement.RELATED)
					.addGroup(gl_panelCentro.createParallelGroup(Alignment.BASELINE)
						.addComponent(txtSenha, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
						.addComponent(txtConfirmaSenha, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
					.addGap(145))
		);
		gl_panelCentro.linkSize(SwingConstants.HORIZONTAL, new Component[] {txtSenha, txtConfirmaSenha});
		gl_panelCentro.linkSize(SwingConstants.HORIZONTAL, new Component[] {lblDadosPessoais, lblContato});
		panelCentro.setLayout(gl_panelCentro);
		{
			panelSul = new JPanel();
			panelSul.setLayout(new FlowLayout(FlowLayout.RIGHT));
			getContentPane().add(panelSul, BorderLayout.SOUTH);
			{
				btnSalvar = new JButton("Salvar");
				btnSalvar.setActionCommand("OK");
				btnSalvar.addActionListener(this);
				
				btnEditar = new JButton("Editar");
				btnEditar.setActionCommand("EDITAR");
				btnEditar.addActionListener(this);
				panelSul.add(btnEditar);
				panelSul.add(btnSalvar);
				getRootPane().setDefaultButton(btnSalvar);
			}
			{
				btnCancelar = new JButton("Cancelar");
				btnCancelar.setActionCommand("Cancel");
				btnCancelar.addActionListener(this);
				panelSul.add(btnCancelar);
			}
		}
		{
			panelNorte = new JPanel();
			panelNorte.setForeground(Color.WHITE);
			panelNorte.setBackground(Color.BLUE);
			getContentPane().add(panelNorte, BorderLayout.NORTH);
			
			lblCadastrarUsuario = new JLabel("Cadastrar Usu\u00E1rio");
			lblCadastrarUsuario.setForeground(Color.WHITE);
			lblCadastrarUsuario.setFont(new Font("Tahoma", Font.BOLD, 18));
			panelNorte.add(lblCadastrarUsuario);
		}
		
	}//inicializaComponentes()
	
	/**
	 * Habilita ou desabilita os campos para edicao
	 * 
	 * True: habilita.
	 * False: desabilita.
	 * 
	 * @param habilita
	 */
	private void habilitaDesabilitaCampos(boolean habilita) {

		txtNomeCompleto.setEnabled(habilita);
		txtDataNascimento.setEnabled(habilita);
		rdbtnMasculino.setEnabled(habilita);
		rdbtnFeminino.setEnabled(habilita);
		txtCpf.setEnabled(habilita);
		txtRgNumero.setEnabled(habilita);
		txtRgOrgao.setEnabled(habilita);
		comboBoxRgUF.setEnabled(habilita);
		
		rdbtnAtivo.setEnabled(habilita);
		rdbtnInativo.setEnabled(habilita);

		txtTelefone.setEnabled(habilita);
		txtCelular.setEnabled(habilita);
		txtEmail.setEnabled(habilita);
		
		txtLogin.setEnabled(habilita);
		txtSenha.setEnabled(habilita);
		txtConfirmaSenha.setEnabled(habilita);

		chckbxUsuarioAdministrador.setEnabled(habilita);
		
		btnSalvar.setEnabled(habilita);

	}//habilitaDesabilitaCampos()
	
	private void preencheCampos() {

		txtNomeCompleto.setText(usuario.getNome());
		txtDataNascimento.setDate(usuario.getDataNascimento().getTime());
		
		if(usuario.getSexo().equalsIgnoreCase(rdbtnMasculino.getActionCommand())) {
			rdbtnMasculino.setSelected(true);
		} else {
			rdbtnFeminino.setSelected(true);
		}
		
		txtCpf.setText(usuario.getCpf());
		txtRgNumero.setText(usuario.getRgNumero());
		txtRgOrgao.setText(usuario.getRgOrgao());
		
		comboBoxRgUF.setSelectedItem(usuario.getRgUF());
		
		if(usuario.getSituacao().equalsIgnoreCase(rdbtnAtivo.getActionCommand())) {
			rdbtnAtivo.setSelected(true);
		} else {
			rdbtnInativo.setSelected(true);
		}
		
		txtTelefone.setText(usuario.getTelefone());
		txtCelular.setText(usuario.getCelular());
		txtEmail.setText(usuario.getEmail());
		
		txtLogin.setText(usuario.getLogin());
		txtSenha.setText("");
		txtConfirmaSenha.setText("");

	}//preencheCampos()
	
	private void editarUsuario(){

		btnEditar.setEnabled(false);
		habilitaDesabilitaCampos(true);
		
	}//editarPaciente()

	private void limparCamposTexto(){

		txtNomeCompleto.setText(null);
		txtDataNascimento.setDate(null);
		txtCpf.setText(null);
		txtRgNumero.setText(null);
		txtRgOrgao.setText(null);
		txtTelefone.setText(null);
		txtCelular.setText(null);
		txtEmail.setText(null);
		txtLogin.setText(null);
		chckbxUsuarioAdministrador.setSelected(false);
		txtSenha.setText(null);
		txtConfirmaSenha.setText(null);

	}//limparCamposTexto()
	
	private void cadastrarUsuario() {

		
		usuario.setNome(txtNomeCompleto.getText());
		usuario.setDataNascimento(txtDataNascimento.getCalendar());
		usuario.setSexo(grupoSexo.getSelection().getActionCommand());
		usuario.setCpf(Formatacao.removerCaracteresCPF(txtCpf.getText()));
		usuario.setRgNumero(txtRgNumero.getText());
		usuario.setRgOrgao(txtRgOrgao.getText());
		usuario.setRgUF((String) comboBoxRgUF.getSelectedItem());
		usuario.setSituacao(grupoSituacao.getSelection().getActionCommand());		
		usuario.setTipoPerfil(Constantes.TIPO_PERFIL_OPERADOR);
		usuario.setTelefone(Formatacao.removerCaracteresTelefone(txtTelefone.getText()));
		usuario.setCelular(Formatacao.removerCaracteresTelefone(txtCelular.getText()));
		usuario.setEmail(txtEmail.getText());
		
		usuario.setLogin(txtLogin.getText());
		usuario.setSenha(Criptografia.criptografaSenha(new String(txtSenha.getPassword())));

		//confirma o cadastro do paciente
		int confirmacao = JOptionPane.showConfirmDialog(this, "Deseja salvar o cadastro do usuário?", "Confirmação de Cadastro", JOptionPane.YES_NO_OPTION);

		if(confirmacao == JOptionPane.YES_OPTION){
			ControladorUsuario controladorUsuario = new ControladorUsuario(this);
			try {
				controladorUsuario.salvar(usuario);
				JOptionPane.showMessageDialog(this, "Cadastro efetuado com sucesso!", "Cadastro", JOptionPane.PLAIN_MESSAGE );
				this.dispose();
			} catch (ControladorExcecao e) {
				if(e.getMessage().equalsIgnoreCase(ControladorExcecao.USUARIO_NULO)){
					e.printStackTrace();
				} else {
					JOptionPane.showMessageDialog(this, e.getMessage(), "Erro de Validação", JOptionPane.OK_OPTION);
				}
			}
			//cria o controlador para fazer as verificacoes e salvar no banco.
			//utilizar try catch para recuperar os erros e mostrar as mensagens ao usuario.
		} else {
			//nao faz nada
		}

	}//cadastrarUsuario()
	
	public void mostraCampoInvalido(JLabel label, boolean status){

		if(status){
			label.setForeground(Color.RED);
		} else {
			label.setForeground(Color.BLACK);
		}

	}//mostraCampoInvalido()
	
	@Override
	public void actionPerformed(ActionEvent event) {
		
		String comando = event.getActionCommand(); 

		if (comando.equalsIgnoreCase(btnSalvar.getActionCommand())) {
			cadastrarUsuario();
		}else if (comando.equalsIgnoreCase(btnEditar.getActionCommand())) {
			editarUsuario();
		} else if (comando.equals(btnCancelar.getActionCommand())) {
			this.dispose();
		}
		
	}

	/**
	 * @return the txtConfirmaSenha
	 */
	public JPasswordField getTxtConfirmaSenha() {
		return txtConfirmaSenha;
	}

	/**
	 * @param txtConfirmaSenha the txtConfirmaSenha to set
	 */
	public void setTxtConfirmaSenha(JPasswordField txtConfirmaSenha) {
		this.txtConfirmaSenha = txtConfirmaSenha;
	}

	/**
	 * @return the lblNomeCompleto
	 */
	public JLabel getLblNomeCompleto() {
		return lblNomeCompleto;
	}

	/**
	 * @param lblNomeCompleto the lblNomeCompleto to set
	 */
	public void setLblNomeCompleto(JLabel lblNomeCompleto) {
		this.lblNomeCompleto = lblNomeCompleto;
	}

	/**
	 * @return the lblDataNascimento
	 */
	public JLabel getLblDataNascimento() {
		return lblDataNascimento;
	}

	/**
	 * @param lblDataNascimento the lblDataNascimento to set
	 */
	public void setLblDataNascimento(JLabel lblDataNascimento) {
		this.lblDataNascimento = lblDataNascimento;
	}

	/**
	 * @return the lblCpf
	 */
	public JLabel getLblCpf() {
		return lblCpf;
	}

	/**
	 * @param lblCpf the lblCpf to set
	 */
	public void setLblCpf(JLabel lblCpf) {
		this.lblCpf = lblCpf;
	}

	/**
	 * @return the lblEmail
	 */
	public JLabel getLblEmail() {
		return lblEmail;
	}

	/**
	 * @param lblEmail the lblEmail to set
	 */
	public void setLblEmail(JLabel lblEmail) {
		this.lblEmail = lblEmail;
	}

	/**
	 * @return the lblLogin
	 */
	public JLabel getLblLogin() {
		return lblLogin;
	}

	/**
	 * @param lblLogin the lblLogin to set
	 */
	public void setLblLogin(JLabel lblLogin) {
		this.lblLogin = lblLogin;
	}

	/**
	 * @return the lblSenha
	 */
	public JLabel getLblSenha() {
		return lblSenha;
	}

	/**
	 * @param lblSenha the lblSenha to set
	 */
	public void setLblSenha(JLabel lblSenha) {
		this.lblSenha = lblSenha;
	}

	/**
	 * @return the lblConfirmacaoSenha
	 */
	public JLabel getLblConfirmacaoSenha() {
		return lblConfirmacaoSenha;
	}

	/**
	 * @param lblConfirmacaoSenha the lblConfirmacaoSenha to set
	 */
	public void setLblConfirmacaoSenha(JLabel lblConfirmacaoSenha) {
		this.lblConfirmacaoSenha = lblConfirmacaoSenha;
	}

	/**
	 * @return the lblRg
	 */
	public JLabel getLblRg() {
		return lblRg;
	}

	/**
	 * @param lblRg the lblRg to set
	 */
	public void setLblRg(JLabel lblRg) {
		this.lblRg = lblRg;
	}

	/**
	 * @return the comboBoxRgUF
	 */
	public JComboBox<String> getComboBoxRgUF() {
		return comboBoxRgUF;
	}

	/**
	 * @param comboBoxRgUF the comboBoxRgUF to set
	 */
	public void setComboBoxRgUF(JComboBox<String> comboBoxRgUF) {
		this.comboBoxRgUF = comboBoxRgUF;
	}
	
	
}
